# _*_ coding: utf-8 _*_
from odoo import models, fields, api
from odoo.exceptions import Warning


class CreateRequestOrder(models.TransientModel):
    _name = "create.purchase.request.order.wizard"

    supplier_id = fields.Many2one("res.partner", string="Supplier", domain=[("supplier", "=", True)])

    def action_ok(self):
        self.ensure_one()
        lines = self.env["purchase.requisition.line"].browse(self.env.context.get("active_ids"))
        if not lines.filtered(lambda line: line.state == 'assign'):
            raise Warning(u'没有已分配的询价任务,无法创建采购询价单。')
        if lines:
            FiscalPosition = self.env['account.fiscal.position']
            fpos = FiscalPosition.get_fiscal_position(self.supplier_id.id)
            fpos = FiscalPosition.browse(fpos)
            vals = {
                "supplier_id": self.supplier_id.id,
                "origin": ', '.join(lines.mapped('requisition_id.name')),
                'payment_term_id': self.supplier_id.property_supplier_payment_term_id and self.supplier_id.property_supplier_payment_term_id.id or False,
                'currency_id': self.supplier_id.property_purchase_currency_id and self.supplier_id.property_purchase_currency_id.id or False,
                'fiscal_position_id': fpos.id
            }
            line_vals = [(0, 0, {
                "product_id": l.product_id.id,
                "product_uom_id": l.product_uom_id.id,
                "price_unit": self._compute_price_unit(l).get('price_unit'),
                "origin_price_unit": self._compute_price_unit(l).get('price_unit'),
                "product_code": self._compute_price_unit(l).get('product_code'),
                "product_name": self._compute_price_unit(l).get('product_name'),
                "product_qty": l.product_qty,
                "delivery_date": fields.Date.today(),
                "requisition_line_id": l.id,
                "requisition_id": l.requisition_id.id,
                "requisition_memo": l.memo,
                'procurement_id': l.requisition_id.procurement_id.id,
                'taxes_id': l.product_id.supplier_taxes_id and [(4, [l.product_id.supplier_taxes_id.ids])] or False
            }) for l in lines if l.state == "assign"]
            vals["line_ids"] = line_vals
            order = self.env["purchase.request.order"].create(vals)
            # req 311
            for o in order:
                o.line_ids._compute_tax_id()
            # end req 311
            return {
                'type': 'ir.actions.act_window',
                'res_model': order._name,
                'res_id': order.id,
                'view_type': 'form',
                'view_mode': 'form',
                'target': 'current'
            }

    def _compute_price_unit(self, line):
        result = dict()
        if not line.product_id:
            result.update({'price_unit': 0})

        seller = line.product_id._select_seller(
            partner_id=self.supplier_id,
            quantity=line.product_qty,
            date=fields.Date.today()[:10],
            uom_id=line.product_uom_id)

        if not seller:
            result.update({'price_unit': 0})

        price_unit = self.env['account.tax']._fix_tax_included_price(seller.price, line.product_id.supplier_taxes_id, line.product_id.supplier_taxes_id and line.product_id.supplier_taxes_id[0]) if seller else 0.0
        if price_unit and seller and self.supplier_id.property_purchase_currency_id and seller.currency_id != self.supplier_id.property_purchase_currency_id:
            price_unit = seller.currency_id.compute(price_unit, self.supplier_id.property_purchase_currency_id)

        if seller and line.product_uom_id and seller.product_uom != line.product_uom_id:
            price_unit = seller.product_uom_id._compute_price(price_unit, line.product_uom_id)

        result.update({'price_unit': price_unit})
        result.update({'product_code': seller.product_code})
        result.update({'product_name': seller.product_name})

        return result
